package com.example.qwen02.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
public class GenerateBackgroundController {
    @GetMapping(value="/getImage2",produces = "application/json;charset=utf-8")
    public String getImage(String task_id) throws IOException {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpGet对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/tasks/" + task_id;

        HttpGet httpGet = new HttpGet(url);

        httpGet.setHeader("Authorization", "Bearer " + System.getenv("DASHSCOPE_API_KEY"));

        try {
            // 执行HTTP Get请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 处理响应
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("Response:" + result);
            response.close();
            return result;
        } finally {
            httpClient.close();
        }
    }

    @PostMapping("/askGenerateBackground")
//    public Map<String, Object> askGenerateBackground(String baseImageUrl,String refImageUrl,String refPrompt)throws IOException{
        public Map<String, Object> askGenerateBackground(String baseImageUrl,String refPrompt)throws IOException{
        System.out.println("baseImageUrl是："+baseImageUrl);
//        System.out.println("refImageUrl是："+refImageUrl);
        System.out.println("refPrompt是："+refPrompt);

        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建HttpPost对象，指定URL
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/background-generation/generation/";
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("X-DashScope-Async", "enable");
        httpPost.setHeader("Authorization", "Bearer " + System.getenv("DASHSCOPE_API_KEY"));
        httpPost.setHeader("Content-Type", "application/json");

        // JSON参数
        String jsonParam = "{\n" +
                "    \"model\": \"wanx-background-generation-v2\",\n" +
                "    \"input\": {\n" +
                "        \"base_image_url\": \""+baseImageUrl+"\",\n" +
//                "        \"ref_image_url\": \""+refImageUrl+"\",\n" +
                "        \"ref_prompt\": \""+refPrompt+"\",\n" +
                "        \"reference_edge\": {\n" +
                "            \"foreground_edge\": [\n" +
                "                \"https://vision-poster.oss-cn-shanghai.aliyuncs.com/lllcho.lc/data/test_data/images/huaban_soft_edge/6cdd13941cef1b11d885aea1717b983ae566b8efc9094-vcsvxa_fw658webp.png\"\n" +
                "            ]\n" +
                "        }\n" +
                "    },\n" +
                "    \"parameters\": {\n" +
                "        \"n\": 1,\n" +
//                "        \"noise_level\": 300,\n" +
//                "        \"ref_prompt_weight\": 0.5,\n" +
                "        \"scene_type\": \"GENERAL\"\n" +
                "    }\n" +
                "}";
        // 将JSON字符串转换为HttpEntity对象并设置到HttpPost中
        httpPost.setEntity(new StringEntity(jsonParam));

        try {
            // 执行HTTP POST请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 处理响应
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity);
            System.out.println("Response:" + result);
            response.close();

            // result是json格式，要提取出其中的task_id
            // 解析整个JSON字符串为一个JSONObject
            JSONObject jsonObject = JSON.parseObject(result);

            Map<String, Object> map = new HashMap<>();
            if (jsonObject.containsKey("output")) {
                // 从JSONObject中获取名为"output"的子对象
                JSONObject outputObject = jsonObject.getJSONObject("output");
                // 从outputObject中提取task_id字段的值
                String taskId = outputObject.getString("task_id");
                map.put("state","success");
                map.put("task_id", taskId);
                System.out.println("提取出的task_id为:"+map.get("task_id"));
            }else{
                map.put("state","error");
                map.put("message",jsonObject.getString("message"));
            }
            return map;
        } finally {
            httpClient.close();
        }
    }
    @PostMapping("/upload2")
    public Map<String, Object> uploadPhoto(MultipartFile photo) throws IOException {
        photo.transferTo(new File("D:\\photos\\"+photo.getOriginalFilename()));
        Map<String, Object> map = new HashMap<>();
        map.put("url", "/ai/photos/"+photo.getOriginalFilename());
        return map;
    }
}
